#include <QThread>

#include "videolinkconverter.h"
#include "ui_videolinkconverter.h"
#include "../database/databasemanager.h"
#include "../youkupageparser.h"

namespace Ui
{
    class VideoLinkConverter;
}

namespace Jcr
{

class VideoLinkConverterPrivate
{
public:
    Ui::VideoLinkConverter* ui;
    QString currentModel;
    Jcr::DatabaseManager* dbMgr;
};

VideoLinkConverter::VideoLinkConverter(QWidget *parent) : QDialog(parent)
{
    d_ptr = new VideoLinkConverterPrivate;
    d_ptr->ui = new Ui::VideoLinkConverter;
    d_ptr->ui->setupUi(this);
    d_ptr->dbMgr = Jcr::DatabaseManager::instance();

    connect(d_ptr->ui->convertButton, SIGNAL(clicked()), this, SLOT(convert()));
    connect(d_ptr->ui->saveButton, SIGNAL(clicked()), this, SLOT(save()));
    connect(d_ptr->ui->modelList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onModelItemClicked(QListWidgetItem*)));

    foreach (auto model, d_ptr->dbMgr->modelsWithVideo()) {
        QListWidgetItem* item = new QListWidgetItem;
        if (d_ptr->dbMgr->modelTrueVideoLinkExists(model))
            item->setTextColor(Qt::green);
        item->setText(model);
        d_ptr->ui->modelList->addItem(item);
    }

//    d_ptr->ui->modelList->addItems(d_ptr->dbMgr->modelsWithVideo());
}

VideoLinkConverter::~VideoLinkConverter()
{
    delete d_ptr;
}

void VideoLinkConverter::convert()
{
    for (int i = 0; i < d_ptr->ui->newMotorLinkList->count(); ++i) {
        Jcr::YoukuPageParser* ypp = new Jcr::YoukuPageParser;
        ypp->setUrl(QUrl(d_ptr->ui->newMotorLinkList->item(i)->text()));

        QThread* thread = new QThread();
        ypp->moveToThread(thread);

        connect(thread, SIGNAL(started()), ypp, SLOT(run()));
        connect(ypp, SIGNAL(finished()), this, SLOT(onGetYoukuLink()));
        connect(ypp, SIGNAL(finished()), thread, SLOT(terminate()));
        connect(ypp, SIGNAL(finished()), thread, SLOT(deleteLater()));

        thread->start();
    }
}

void VideoLinkConverter::save()
{
    int trueLinkCount = d_ptr->ui->trueLinkList->count();
    for (int i = 0; i < trueLinkCount; ++i)
        d_ptr->dbMgr->addModelVideoTrueLink(d_ptr->currentModel, d_ptr->ui->trueLinkList->item(i)->text());
}

void VideoLinkConverter::onModelItemClicked(QListWidgetItem *item)
{
    d_ptr->ui->newMotorLinkList->clear();
    d_ptr->ui->trueLinkList->clear();
    item->setTextColor(Qt::magenta);

    const QString& model = item->text();
    d_ptr->currentModel = model;
    QStringList videoLinks = d_ptr->dbMgr->modelVideoLinks(model);
    d_ptr->ui->newMotorLinkList->addItems(videoLinks);

}

void VideoLinkConverter::onGetYoukuLink()
{
    Jcr::YoukuPageParser* ypp = qobject_cast<Jcr::YoukuPageParser*>(sender());
    QString link = ypp->youkuLink();
    d_ptr->ui->trueLinkList->addItem(link);
    ypp->deleteLater();
}

} // namespace jcr
